﻿using System.Diagnostics.Contracts;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using DaveSexton.Labs;

namespace $safeprojectname$
{
  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    internal PhoneLabController LabController
    {
      get
      {
        return controller;
      }
    }

    private PhoneLabController controller;
    private PhoneApplicationFrame rootFrame;
    private bool phoneApplicationInitialized;

    public App()
    {
      UnhandledException += Application_UnhandledException;

      // Show graphics profiling information while debugging.
      if (System.Diagnostics.Debugger.IsAttached)
      {
        // Display the current frame rate counters
        Application.Current.Host.Settings.EnableFrameRateCounter = true;

        // Show the areas of the app that are being redrawn in each frame.
        //Application.Current.Host.Settings.EnableRedrawRegions = true;

        // Enable non-production analysis visualization mode, 
        // which shows areas of a page that are being GPU accelerated with a colored overlay.
        //Application.Current.Host.Settings.EnableCacheVisualization = true;
      }

      // Standard Silverlight initialization
      InitializeComponent();

      // Phone-specific initialization
      InitializePhoneApplication();
    }

    private void InitializePhoneApplication()
    {
      if (phoneApplicationInitialized)
        return;

      rootFrame = new PhoneApplicationFrame();

      rootFrame.Navigated += CompleteInitializePhoneApplication;
      rootFrame.NavigationFailed += RootFrame_NavigationFailed;

      phoneApplicationInitialized = true;
    }

    private void Application_Launching(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e)
    {
      var catalog = new Catalog();

      controller = new PhoneLabController(catalog);
    }

    private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
      if (System.Diagnostics.Debugger.IsAttached)
      {
        System.Diagnostics.Debugger.Break();
      }
    }

    private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
    {
      if (System.Diagnostics.Debugger.IsAttached)
      {
        System.Diagnostics.Debugger.Break();
      }
    }

    private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
    {
      if (RootVisual != rootFrame)
        RootVisual = rootFrame;

      rootFrame.Navigated -= CompleteInitializePhoneApplication;
    }
  }
}